package com.example.servlet;

import com.example.model.QuizQuestion;
import com.example.util.DBUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
import java.text.SimpleDateFormat;

public class QuizServlet extends HttpServlet {
    
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) 
            throws ServletException, IOException {
        HttpSession session = request.getSession(false);
        // 支持user对象或user_id
        Object userObj = (session != null) ? session.getAttribute("user") : null;
        Integer userId = (session != null && session.getAttribute("user_id") != null) ? (Integer) session.getAttribute("user_id") : null;
        if (userObj == null && userId == null) {
            response.sendRedirect("login.jsp");
            return;
        }
        try (Connection conn = DBUtil.getConnection()) {
            // 检查今日答题次数
            java.sql.Date today = new java.sql.Date(System.currentTimeMillis());
            int attemptCount = 0;
            try (PreparedStatement ps = conn.prepareStatement("SELECT attempt_count FROM quiz_attempts WHERE user_id=? AND attempt_date=?")) {
                ps.setInt(1, userId);
                ps.setDate(2, today);
                ResultSet rs = ps.executeQuery();
                if (rs.next()) attemptCount = rs.getInt(1);
            }
            if (attemptCount >= 3) {
                request.setAttribute("error", "今日答题次数已用完，请明天再来！");
                request.getRequestDispatcher("/quiz.jsp").forward(request, response);
                return;
            }
            List<QuizQuestion> questions = new ArrayList<>();
            // 1. 优先抽取错题本
            if (userId != null) {
                String wrongSql = "SELECT qq.* FROM wrong_questions wq JOIN quiz_questions qq ON wq.question_id=qq.id WHERE wq.user_id=? ORDER BY RAND() LIMIT 3";
                PreparedStatement wrongStmt = conn.prepareStatement(wrongSql);
                wrongStmt.setInt(1, userId);
                ResultSet wrs = wrongStmt.executeQuery();
                while (wrs.next()) {
                    QuizQuestion question = new QuizQuestion();
                    question.setId(wrs.getInt("id"));
                    question.setQuestion(wrs.getString("question"));
                    question.setOptionA(wrs.getString("option_a"));
                    question.setOptionB(wrs.getString("option_b"));
                    question.setOptionC(wrs.getString("option_c"));
                    question.setOptionD(wrs.getString("option_d"));
                    question.setAnswer(wrs.getString("answer"));
                    question.setType(wrs.getString("type"));
                    questions.add(question);
                }
            }
            // 2. 错题不足3道，随机补足
            if (questions.size() < 3) {
                String randomSql = "SELECT * FROM quiz_questions ORDER BY RAND() LIMIT ?";
                PreparedStatement randomStmt = conn.prepareStatement(randomSql);
                randomStmt.setInt(1, 3 - questions.size());
                ResultSet rrs = randomStmt.executeQuery();
                while (rrs.next()) {
                    QuizQuestion question = new QuizQuestion();
                    question.setId(rrs.getInt("id"));
                    question.setQuestion(rrs.getString("question"));
                    question.setOptionA(rrs.getString("option_a"));
                    question.setOptionB(rrs.getString("option_b"));
                    question.setOptionC(rrs.getString("option_c"));
                    question.setOptionD(rrs.getString("option_d"));
                    question.setAnswer(rrs.getString("answer"));
                    question.setType(rrs.getString("type"));
                    questions.add(question);
                }
            }
            request.setAttribute("quizList", questions);
            request.getRequestDispatcher("/quiz.jsp").forward(request, response);
        } catch (SQLException e) {
            request.setAttribute("error", "获取测验题目失败: " + e.getMessage());
            request.getRequestDispatcher("/quiz.jsp").forward(request, response);
        }
    }
    
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) 
            throws ServletException, IOException {
        HttpSession session = request.getSession(false);
        Object userObj = (session != null) ? session.getAttribute("user") : null;
        Integer userId = (session != null && session.getAttribute("user_id") != null) ? (Integer) session.getAttribute("user_id") : null;
        if (userObj == null && userId == null) {
            response.sendRedirect("login.jsp");
            return;
        }
        try (Connection conn = DBUtil.getConnection()) {
            // 检查今日答题次数
            java.sql.Date today = new java.sql.Date(System.currentTimeMillis());
            int attemptCount = 0;
            try (PreparedStatement ps = conn.prepareStatement("SELECT attempt_count FROM quiz_attempts WHERE user_id=? AND attempt_date=?")) {
                ps.setInt(1, userId);
                ps.setDate(2, today);
                ResultSet rs = ps.executeQuery();
                if (rs.next()) attemptCount = rs.getInt(1);
            }
            if (attemptCount >= 3) {
                request.setAttribute("error", "今日答题次数已用完，请明天再来！");
                request.getRequestDispatcher("/quiz.jsp").forward(request, response);
                return;
            }
            String[] answers = request.getParameterValues("answer");
            String[] questionIds = request.getParameterValues("qid");
            if (answers == null || questionIds == null) {
                request.setAttribute("error", "请回答所有问题");
                request.getRequestDispatcher("/quiz.jsp").forward(request, response);
                return;
            }
            int correctCount = 0;
            int totalQuestions = questionIds.length;
            List<QuizResultDetail> detailList = new ArrayList<>();
            for (int i = 0; i < questionIds.length; i++) {
                String questionId = questionIds[i];
                String userAnswer = answers[i];
                String sql = "SELECT question, option_a, option_b, option_c, option_d, answer, explanation, type FROM quiz_questions WHERE id = ?;";
                PreparedStatement stmt = conn.prepareStatement(sql);
                stmt.setString(1, questionId);
                ResultSet rs = stmt.executeQuery();
                if (rs.next()) {
                    String correctAnswer = rs.getString("answer");
                    boolean isCorrect = userAnswer.equals(correctAnswer);
                    if (isCorrect) correctCount++;
                    QuizResultDetail detail = new QuizResultDetail();
                    detail.setQuestion(rs.getString("question"));
                    detail.setOptionA(rs.getString("option_a"));
                    detail.setOptionB(rs.getString("option_b"));
                    detail.setOptionC(rs.getString("option_c"));
                    detail.setOptionD(rs.getString("option_d"));
                    detail.setUserAnswer(userAnswer);
                    detail.setCorrectAnswer(correctAnswer);
                    detail.setCorrect(isCorrect);
                    detail.setExplanation(rs.getString("explanation"));
                    detail.setType(rs.getString("type"));
                    detailList.add(detail);
                    if (!isCorrect && userId != null) {
                        String insertSql = "INSERT INTO wrong_questions (user_id, question_id, user_answer, correct_answer) VALUES (?, ?, ?, ?) ON DUPLICATE KEY UPDATE user_answer=?, correct_answer=?;";
                        PreparedStatement insertStmt = conn.prepareStatement(insertSql);
                        insertStmt.setInt(1, userId);
                        insertStmt.setString(2, questionId);
                        insertStmt.setString(3, userAnswer);
                        insertStmt.setString(4, correctAnswer);
                        insertStmt.setString(5, userAnswer);
                        insertStmt.setString(6, correctAnswer);
                        insertStmt.executeUpdate();
                    }
                }
            }
            // 更新答题次数
            try (PreparedStatement ps = conn.prepareStatement("INSERT INTO quiz_attempts (user_id, attempt_date, attempt_count) VALUES (?, ?, 1) ON DUPLICATE KEY UPDATE attempt_count=attempt_count+1, last_attempt_time=NOW()")) {
                ps.setInt(1, userId);
                ps.setDate(2, today);
                ps.executeUpdate();
            }
            int score = (int) ((double) correctCount / totalQuestions * 100);
            request.setAttribute("score", score);
            request.setAttribute("correctCount", correctCount);
            request.setAttribute("totalQuestions", totalQuestions);
            request.setAttribute("resultMsg", "答对 " + correctCount + "/" + totalQuestions + " 题，得分：" + score);
            request.setAttribute("detailList", detailList);
            request.getRequestDispatcher("/quiz.jsp").forward(request, response);
        } catch (SQLException e) {
            request.setAttribute("error", "提交答案失败: " + e.getMessage());
            request.getRequestDispatcher("/quiz.jsp").forward(request, response);
        }
    }

    // 答题结果详情内部类
    public static class QuizResultDetail {
        private String question, optionA, optionB, optionC, optionD, userAnswer, correctAnswer, explanation, type;
        private boolean correct;
        public String getQuestion() { return question; }
        public void setQuestion(String question) { this.question = question; }
        public String getOptionA() { return optionA; }
        public void setOptionA(String optionA) { this.optionA = optionA; }
        public String getOptionB() { return optionB; }
        public void setOptionB(String optionB) { this.optionB = optionB; }
        public String getOptionC() { return optionC; }
        public void setOptionC(String optionC) { this.optionC = optionC; }
        public String getOptionD() { return optionD; }
        public void setOptionD(String optionD) { this.optionD = optionD; }
        public String getUserAnswer() { return userAnswer; }
        public void setUserAnswer(String userAnswer) { this.userAnswer = userAnswer; }
        public String getCorrectAnswer() { return correctAnswer; }
        public void setCorrectAnswer(String correctAnswer) { this.correctAnswer = correctAnswer; }
        public boolean isCorrect() { return correct; }
        public void setCorrect(boolean correct) { this.correct = correct; }
        public String getExplanation() { return explanation; }
        public void setExplanation(String explanation) { this.explanation = explanation; }
        public String getType() { return type; }
        public void setType(String type) { this.type = type; }
    }
} 